package io.renren.controller;

import io.renren.annotation.Login;
import io.renren.cloud.OSSFactory;
import io.renren.common.exception.RRException;
import io.renren.common.utils.R;
import io.renren.entity.JxStudentHomworkEntity;
import io.renren.service.JxStudentHomworkService;
import io.renren.service.SysOssService;
import io.renren.utils.ConfigConstant;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.util.Date;

/**
 * 学生作业
 */
@RestController
@RequestMapping("/api/homwork")
public class ApiStudentHomworkController {
    @Autowired
    private SysOssService sysOssService;
    @Autowired
    private JxStudentHomworkService homworkService;


    private final static String KEY = ConfigConstant.CLOUD_STORAGE_CONFIG_KEY;
    @Login
    @ApiOperation("提交作业")
    @RequestMapping(value = "/submit", method = RequestMethod.POST)
    public R submitHomwork(@RequestParam("file") MultipartFile file, Long studentId, Long courseId, String name, Long teacherId, String courseDay, Long deviceId) {
        if (file.isEmpty()) {
            throw new RRException("上传文件不能为空");
        }


        if(null!=studentId&&null!=courseId&&null!=name&&null!=teacherId&&null!=courseDay&&null!=deviceId){
        try {
            //上传文件
            String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
            //aliyun上传文件
            String url = OSSFactory.build().uploadSuffix(file.getInputStream(),suffix);
          if(url!=null&&url.length()>0){
              //保存文件信息
              JxStudentHomworkEntity entity=new JxStudentHomworkEntity();
              entity.setStudentId(studentId);
              entity.setCourseId(courseId);
              entity.setName(name);
              entity.setTeacherId(teacherId);
              entity.setCourseDay(courseDay);
              entity.setDeviceId(deviceId);
              entity.setUploadTime(new Date());
              entity.setFileUrl(url);
              homworkService.save(entity);
              //表单校验
              return R.ok();
          }else{
              return  R.error("请联系管理员！");
          }


        } catch (Exception e) {
            return R.error();
        }
        }return R.error().put("msg","缺少必要的参数无法上传");


    }
}
